/*
 * Licensed under the Apache License, Version 2.0 (the "License"):
 *    http://www.apache.org/licenses/LICENSE-2.0
 */
package {
import com.google.maps.controls.ControlBase;
import com.google.maps.controls.ControlPosition;
import com.google.maps.interfaces.IMap;
import com.google.maps.overlays.*;

import flash.events.Event;
import flash.net.URLLoader;
import flash.net.URLRequest;

import mx.containers.VBox;
import mx.controls.CheckBox;
import mx.controls.LinkButton;
import mx.controls.TextArea;

public class MapLegend extends ControlBase {

    private var textArea:TextArea;
    private var tileLayer:TileLayerOverlay;
    private var nasaLabel:LinkButton;

    /**
     * Constructor of custom control.
     * @constructor.
     */
    public function MapLegend(tileLayer:TileLayerOverlay,
                              nasaLabel:LinkButton) {
        // Control will be placed at the top left corner of the map,
        // 10 pixels from the edges.
        this.tileLayer = tileLayer;
        this.nasaLabel = nasaLabel;
        super(new ControlPosition(ControlPosition.ANCHOR_TOP_RIGHT, 410, 8));
    }

    public override function initControlWithMap(map:IMap):void {
        var box:VBox = new VBox();
        box.width = 125;
        box.height = 25;
        box.setStyle("backgroundColor", "#FFFFFF");
        box.setStyle("paddingLeft", 5);
        box.setStyle("borderColor", "#000000");
        box.setStyle("borderThickness", 1);
        box.setStyle("borderStyle", "solid");
        var checkbox:CheckBox = new CheckBox();
        checkbox.label = "Recent Imagery";
        checkbox.selected = false;
        box.addChild(checkbox);
        addChild(box);

        checkbox.addEventListener("click", function(e:Event):void {
            if (checkbox.selected) {
                map.addOverlay(tileLayer);
                var updateString:URLRequest = new URLRequest(
                        "http://mapvisage.appspot.com/tiles/lastupdated?tiles=nasa");
                var updateLoader:URLLoader = new URLLoader();
                updateLoader.addEventListener("complete",
                        function(e:Event):void {
                            nasaLabel.label = "Image from MODIS NASA/GSFC"
                                    + " (Updated " + updateLoader.data + ")";
                        });
                updateLoader.load(updateString);
            } else {
                map.removeOverlay(tileLayer);
            }
        });
    }
}
}
